/* eslint-disable no-loop-func */
import { insertJQuery } from '../../lib/utils.js';

// 同步申报表信息及申报表
class SyncReportInfoHelper {
  /**
   * 抓取待办事项
   */
  captureTodo() {
    const trs = $('.z-table:visible .z-mt  tbody tr').toArray();
    return trs
      .map(tr => {
        const tds = $(tr)
          .find('td:visible')
          .toArray();
        let declareType = tds[1].innerText.trim();

        if (declareType.includes('企业所得税')) {
          declareType = /季|月/.test(declareType)
            ? '企业所得税月(季)'
            : '企业所得税年';
        }

        if (declareType.includes('适用执行') || !declareType) {
          declareType = `财务报表(${declareType})`;
        }

        if (declareType.includes('城建税、教育费附加、地方教育附加税')) {
          declareType = '城建税、教育费附加、地方教育附加税';
        }
        declareType = this.replaceSpecialSign(declareType);
        const declareTime = '';
        const state = tds[5].innerText.trim().includes('成功')
          ? '已申报'
          : '未申报';
        return {
          declareTime,
          declareType,
          state
        };
      })
      .filter(item =>
        /增值税|财务报表|附加税|企业所得税/.test(item.declareType));
  }

  /**
   * 从页面中获取报表信息
   */
  async captureDataFromPage() {
    let reportInfoFromTodo = this.captureTodo();
    console.log('success', reportInfoFromTodo);
    if (!reportInfoFromTodo.length) {
      alert('请本期申报完成后，再同步申报表信息！');
    }
    window.postMessage(
      {
        event: 'syncReportInfoInSaas',
        data: {
          syncReportInfo: reportInfoFromTodo
        }
      },
      '*'
    );
  }

  /**
   * 开始同步申报表信息
   */
  startGetReportInfo() {
    if (!/https:\/\/etax.hunan.chinatax.gov.cn\//.test(window.location.href)) {
      alert('请在首页进行同步申报种类！');
      return;
    }
    if (
      /\/web-accept\/wssb\/common\/dzsb.html/.test(window.location.pathname)
    ) {
      window.view('nssb');
      setTimeout(function() {
        syncReportInfoHelper.captureDataFromPage();
      }, 1000);
    } else {
      window.open('/web-accept/wssb/common/dzsb.html');
    }
  }

  fixDisplay(result, start) {
    return result.reduce(
      (r, table) => [
        ...r, table.slice(0, start), table.slice(start, table.length)
      ],
      []
    );
  }

  /**
   * 开始同步申报表
   */
  async startGetReport() {
    let iframeWindow;

    if (
      !/\/web-accept\/wssb\/common\/dzsb.html/.test(window.location.pathname)
    ) {
      alert('请到对应的申报界面进行同步申报表');
      return;
    }
    iframeWindow = $('.layui-layer-content iframe')[0]
      && $('.layui-layer-content iframe')[0].contentWindow;

    if (!iframeWindow) {
      alert('请打开需要同步的申报表');
      return;
    }

    let tables;
    tables = iframeWindow.$('.main table table').toArray();

    let result = [...tables].map(table =>
      this.transformTableToArray(table, iframeWindow.$));

    let declareType = iframeWindow
      .$('.lefttitle')
      .text()
      .trim()
      .replace('城市维护建设税', '城建税');
    declareType = this.replaceSpecialSign(declareType);
    declareType = this.replaceName(declareType);

    if (declareType.includes('增值税')) {
      result = this.fixDisplay(result, 4);
    }
    if (declareType.includes('附加税')) {
      result = this.fixDisplay(
        result.map(t => t.map(r => r.slice(1, r.length))).filter(t => t.length),
        3
      );
    }
    if (declareType.includes('所得税')) {
      // 修正处理
      result = this.fixDisplay(
        result.map(t => t.map(r => r.slice(1, r.length))).filter(t => t.length),
        7
      );
      result = [
        ...this.fixDisplay([result[0]], 4), ...result.slice(1, result.length)
      ];
    }

    console.log(result);
    window.postMessage(
      {
        event: 'syncReportInSaas',
        data: {
          detail: result,
          state: '已申报',
          declareType
        }
      },
      '*'
    );
  }

  /**
   * 将dom转换为二维数组
   * @param {Array} table
   * @param {Object} $
   */
  transformTableToArray(table, $ = window.$) {
    // 集合所有tr即每一行
    const trs = $(table)
      .find('tr:visible')
      .toArray();

    // 构建二维数组，并构建每一行每一列的数据
    const result = trs
      .map(tr => {
        let tds = $(tr)
          .find('td:visible')
          .toArray();
        if (tds && tds.length) {
          tds = tds.map(td => {
            const $td = $(td);
            const inputs = $td.find('input');
            let val = '';
            // 若存在input，则为输入框
            if (inputs.length) {
              // 获取输入
              val = $(inputs[0]).val();
              if (['N', 'Y'].includes(val)) {
                val = val === 'N' ? '否' : '是';
              }
              let text = $td.text().replace(/\s/g, '');
              // 存在文本+输入框情况 需都抓取 排除-- （数额为空填充）
              if (text && text !== '--') {
                val = text + val;
              }
            } else {
              val = $td.text().replace(/\s/g, '');
            }
            // return val;
            return {
              val,
              rowspan: $td.attr('rowspan') || '1',
              colspan: $td.attr('colspan') || '1'
            };
          });
        }
        return tds;
      })
      .filter(tr => !tr.every(td => !td.val));
    return result;
  }

  /**
   * 替换特殊符号
   * @param {String} str
   */
  replaceSpecialSign(str) {
    return str.replace(/（/g, '(').replace(/）/g, ')');
  }

  replaceName(name) {
    const names = [
      '企业所得税月', '企业所得税年', '增值税', '个人所得税', '财务报表', '附加税'
    ];
    return names.find(n => name.includes(n));
  }
}

const syncReportInfoHelper = new SyncReportInfoHelper();

export { syncReportInfoHelper };
